package com.tronsis.distribution.activity.me.order;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.CollectionWayActivity;
import com.tronsis.distribution.activity.me.PaymentVoucherActivity;
import com.tronsis.distribution.activity.me.address.AddressManageActivity;
import com.tronsis.distribution.bean.AddressBean;
import com.tronsis.distribution.bean.AskBuyBean;
import com.tronsis.distribution.bean.AskBuyDetailBean;
import com.tronsis.distribution.bean.PayeeMethodBean;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.CommonFactory;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.eventbus.EventMessage;
import com.tronsis.distribution.eventbus.EventTag;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.pay.wechatpay.WeChatPayOrderBean;
import com.tronsis.distribution.pay.wechatpay.WechatPay;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.distribution.wxapi.WXPayEntryActivity;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.db.DBUtil;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.util.WindowUtil;
import com.tronsis.library.widget.ConfirmDialog;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

public class OrderDetailActivity extends ToolBarBaseActivity {
    @BindView(R.id.rv_goods)
    RecyclerView mRvGoods;
    @BindView(R.id.tv_more)
    TextView mTvMore;
    @BindView(R.id.tv_amount)
    TextView mTvAmount;
    @BindView(R.id.tv_order_num)
    TextView mTvOrderNum;
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_leader_name)
    TextView mTvLeaderName;
    @BindView(R.id.tv_account)
    TextView mTvAccount;
    @BindView(R.id.tv_payee)
    TextView mTvPayee;
    @BindView(R.id.ll_pay_type)
    LinearLayout mLlPayType;
    @BindView(R.id.tv_is_use_point)
    TextView mTvIsUsePoint;
    @BindView(R.id.et_points)
    EditText mEtPoints;
    @BindView(R.id.tv_pay_actual)
    TextView mTvPayActual;
    @BindView(R.id.ll_pay_voucher)
    LinearLayout mLlPayVoucher;
    @BindView(R.id.ll_pay_image)
    LinearLayout mLlPayImage;
    @BindView(R.id.tv_label_pay_image)
    TextView mTvLabelPayImage;
    @BindView(R.id.rv_user_upload)
    RecyclerView mRvUserUpload;
    @BindView(R.id.ll_use_points)
    LinearLayout mLlUsePoints;
    @BindView(R.id.ll_pay_actual)
    LinearLayout mLlPayActual;
    @BindView(R.id.ll_amount)
    LinearLayout mLlAmount;
    @BindView(R.id.ll_points)
    LinearLayout mLlPoints;
    @BindView(R.id.ll_pay_info)
    LinearLayout mLlPayInfo;
    @BindView(R.id.view_deliver)
    View mViewDeliver;
    @BindView(R.id.iv_right1)
    ImageView mIvRight1;
    @BindView(R.id.iv_right2)
    ImageView mIvRight2;
    @BindView(R.id.iv_right3)
    ImageView mIvRight3;
    @BindView(R.id.iv_coupons)
    ImageView mIvCoupons;
    @BindView(R.id.ll_coupons)
    LinearLayout mLlCoupons;
    @BindView(R.id.rv_refund)
    RecyclerView mRvRefund;
    @BindView(R.id.ll_refund_image)
    LinearLayout mLlRefundImage;
    @BindView(R.id.cb_wechat_pay)
    CheckBox mCbWechatPay;
    @BindView(R.id.ll_wechat_pay)
    LinearLayout mLlWechatPay;
    @BindView(R.id.ll_pay_way)
    LinearLayout mLlPayWay;
    @BindView(R.id.cb_offline_pay)
    CheckBox mCbOfflinePay;
    @BindView(R.id.ll_offline_pay)
    LinearLayout mLlOfflinePay;
    @BindView(R.id.view_line)
    View mViewLine;
    @BindView(R.id.btn_pay)
    Button mBtnPay;
    @BindView(R.id.tv_pay_way)
    TextView mTvPayWay;
    @BindView(R.id.ll_paid_type)
    LinearLayout mLlPaidType;
    @BindView(R.id.ll_account)
    LinearLayout mLlAccount;
    @BindView(R.id.ll_leader_name)
    LinearLayout mLlLeaderName;
    @BindView(R.id.lly_address)
    LinearLayout mLlyAddress;
    @BindView(R.id.ll_address_info)
    LinearLayout mLlAddressInfo;
    @BindView(R.id.tv_address_name)
    TextView mTvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView mTvAddressPhone;
    @BindView(R.id.tv_address)
    TextView mTvAddress;

    private AskBuyBean mAskBuyBean;
    private AskBuyDetailBean mAskBuyDetailBean;

    private PopupWindow mUsePointPopupWindow;
    private CommonAdapter<AskBuyDetailBean.ItemsBean> mAdapter;
    private List<AskBuyDetailBean.ItemsBean> mGoodsList = new ArrayList<>();
    private List<AskBuyDetailBean.ItemsBean> mGoodsAllList = new ArrayList<>();
    private List<AskBuyDetailBean.ItemsBean> mGoodsPartList = new ArrayList<>();

    private ArrayList<ImageItem> mImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mPayImageAdapter;
    private boolean mShowDelete = false;

    private ArrayList<ImageItem> mRefundImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mRefundImageAdapter;

    private String mPayeeId;
    private double mPointCovert = 0;
    private String mType;
    private Integer mPoints = 0;
    private String addrId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);

        ButterKnife.bind(this);
        setTitle(true, getString(R.string.order_detail), getString(R.string.submit));
        mTvRight.setVisibility(View.GONE);

        initView();
        initImageRv();
        initRefundImageRv();

        mAskBuyBean = (AskBuyBean) getIntent().getSerializableExtra("AskBuyBean");
        mType = getIntent().getType();
        if (StringUtil.isEquals(mType, "processing")) {
            mLlPayInfo.setVisibility(View.GONE);
            mViewDeliver.setVisibility(View.VISIBLE);

            if (StringUtil.isEquals(mAskBuyBean.getState(), StateUtil.MY_STOCK_ORDER_PAY)) {
                mLlPayImage.setVisibility(View.GONE);
                mLlUsePoints.setVisibility(View.GONE);
                mLlPayActual.setVisibility(View.GONE);
            }
        }

        if (mAskBuyBean != null) {
            setSateView(mAskBuyBean.getState());
            if (StringUtil.isEquals(mAskBuyBean.getState(), StateUtil.MY_STOCK_ORDER_PAY) && StringUtil.isEquals(mType, "my")) {
                UserBean userBean = UserBizFactory.createBiz().getLoginUser(OrderDetailActivity.this);
                mPoints = userBean.getPoints();
                mEtPoints.setHint(getString(R.string.format_max_points_use, userBean.getPoints()));
                if (mAskBuyBean.getCouponId() != null) {
                    mLlyAddress.setVisibility(View.VISIBLE);
                } else {
                    mLlyAddress.setVisibility(View.GONE);
                }
                httpGetMyPoints();

                httpGetPointConvert();
            }

            httpGetDetail(mAskBuyBean.getId());
        }

        // 微信回调 注册广播接收
        IntentFilter filter = new IntentFilter();
        filter.addAction(WXPayEntryActivity.WX_PAY_RESULT_ACTION);
        registerReceiver(payBroadcastReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(payBroadcastReceiver);
        super.onDestroy();
    }

    private void setSateView(String state) {
        if (state == null) {
            return;
        }

        if (StringUtil.isEquals(state, StateUtil.MY_STOCK_ORDER_PAY) && StringUtil.isEquals(mType, "my")) {
            setPointEditText();
//            mTvRight.setVisibility(View.VISIBLE); //提交按钮（原来）
            mLlPayType.setEnabled(true);
            mLlUsePoints.setEnabled(true);
//            mLlPayVoucher.setVisibility(View.VISIBLE);
            mIvRight1.setVisibility(View.VISIBLE);
            mIvRight2.setVisibility(View.VISIBLE);
            mIvRight3.setVisibility(View.VISIBLE);
            mTvLabelPayImage.setVisibility(View.GONE);
            mBtnPay.setVisibility(View.VISIBLE);
            mLlPayInfo.setVisibility(View.GONE);
//            //公司
//            double realPay = mAskBuyDetailBean == null ? 0 : mAskBuyDetailBean.getPaidPrice();
//            setPayWay(realPay);
            if (mAskBuyDetailBean != null) {
                setPayWay(mAskBuyDetailBean.getSupportPay());
            }
        } else {
            mEtPoints.setFocusable(false);
            mEtPoints.setFocusableInTouchMode(false);
            mTvRight.setVisibility(View.GONE);
            mLlPayType.setEnabled(false);
            mLlUsePoints.setEnabled(false);
            mLlPayVoucher.setVisibility(View.GONE);
            mIvRight1.setVisibility(View.GONE);
            mIvRight2.setVisibility(View.GONE);
            mIvRight3.setVisibility(View.GONE);
            mTvLabelPayImage.setVisibility(View.VISIBLE);
            mLlPayWay.setVisibility(View.GONE);
        }

        //公司 优惠券
        if (mAskBuyBean != null && mAskBuyBean.getCouponId() != null) {
            mRvGoods.setVisibility(View.GONE);
            mLlAmount.setVisibility(View.GONE);
            mLlPayActual.setVisibility(View.GONE);
            mLlCoupons.setVisibility(View.VISIBLE);
            ImageLoader.display(mContext, Url.FILE_DOWNLOAD + mAskBuyBean.getCouponCoverFid(), mIvCoupons);
        }

    }

    private void setPayWay(double realPay) {
        if (mAskBuyDetailBean != null && mAskBuyDetailBean.getLeaderName() == null) {
            //公司
            mLlPayWay.setVisibility(View.VISIBLE);
            if (realPay < 10000) {
                mLlOfflinePay.setVisibility(View.GONE);
                mLlWechatPay.setVisibility(View.VISIBLE);
            } else {
                mLlOfflinePay.setVisibility(View.VISIBLE);
                mLlWechatPay.setVisibility(View.VISIBLE);
            }
        } else {
            mLlPayWay.setVisibility(View.VISIBLE);
            mLlWechatPay.setVisibility(View.GONE);
            mLlOfflinePay.setVisibility(View.VISIBLE);
        }
    }

    private void setPayWay(int supportPay) {
        switch (supportPay) {
            case 0:
                mLlPayWay.setVisibility(View.VISIBLE);
                mLlOfflinePay.setVisibility(View.GONE);
                mLlWechatPay.setVisibility(View.VISIBLE);
                break;
            case 1:
                mLlPayWay.setVisibility(View.VISIBLE);
                mLlOfflinePay.setVisibility(View.VISIBLE);
                mLlWechatPay.setVisibility(View.VISIBLE);
                break;
            case 2:
                mLlPayWay.setVisibility(View.VISIBLE);
                mLlOfflinePay.setVisibility(View.VISIBLE);
                mLlWechatPay.setVisibility(View.GONE);
                break;
        }

    }

    private void setPointEditText() {
        mEtPoints.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String pointStr = mEtPoints.getText().toString();
                if (mAskBuyDetailBean != null && !TextUtils.isEmpty(pointStr)) {
                    Integer point = Integer.valueOf(pointStr);
                    if (point > mPoints) {
                        ToastUtil.showMessage(mContext, "积分不能超过" + mPoints);
                    }
                    double realPay = mAskBuyDetailBean.getTotalPrice() - mPointCovert * point;
                    realPay = realPay < 0 ? 0 : realPay;
                    mTvPayActual.setText(getString(R.string.format_rmb, realPay));
//                    setPayWay(realPay);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    private void initView() {
        mTvRight.setVisibility(View.GONE);
        mLlPayType.setEnabled(false);

        mCbWechatPay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mCbOfflinePay.isShown() && isChecked) {
                    mCbOfflinePay.setChecked(false);
                }
            }
        });
        mCbOfflinePay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mCbWechatPay.isShown() && isChecked) {
                    mCbWechatPay.setChecked(false);
                }
            }
        });


        mAdapter = new CommonAdapter<AskBuyDetailBean.ItemsBean>(mContext, mGoodsList, R.layout.item_order_goods) {
            @Override
            protected void convert(ViewHolder holder, AskBuyDetailBean.ItemsBean bean, int position) {
                holder.setImageByUrl(mContext, R.id.iv_cover, Url.FILE_DOWNLOAD + bean.getCoverFid());
                holder.setText(R.id.tv_title, bean.getName());
                holder.setText(R.id.tv_count, "x" + bean.getAmount());
                if (StateUtil.getResSate(mContext, bean.getProductState()).equals("已下架")) {
                    holder.setText(R.id.tv_state, StateUtil.getResSate(mContext, bean.getProductState()));
                    holder.setVisible(R.id.tv_state, true);
                    holder.setVisible(R.id.tv_count, false);
                } else {
                    holder.setVisible(R.id.tv_state, false);
                    holder.setVisible(R.id.tv_count, true);
                }
            }
        };


        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvGoods.addItemDecoration(decoration);
        mRvGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mRvGoods.setHasFixedSize(true);
        mRvGoods.setNestedScrollingEnabled(false);
        mRvGoods.setAdapter(mAdapter);
    }

    private void initImageRv() {
        mPayImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);
                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteConfirmDialog(position);
                    }
                });


                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }

                    /*ivItem.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            if (mShowDelete) {
                                mShowDelete = false;
                            } else {
                                mShowDelete = true;
                            }
                            notifyDataSetChanged();
                            return false;
                        }
                    });
*/
                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mImageList.get(position).path) && TextUtils.isEmpty(mImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(OrderDetailActivity.this, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });

                if (mShowDelete) {
                    holder.getView(R.id.iv_delete).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.iv_delete).setVisibility(View.GONE);
                }
            }


        };


        mRvUserUpload.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvUserUpload.setAdapter(mPayImageAdapter);
        mRvUserUpload.setHasFixedSize(true);
        mRvUserUpload.setNestedScrollingEnabled(false);
    }

    private void initRefundImageRv() {
        mRefundImageAdapter = new CommonAdapter<ImageItem>(mContext, mRefundImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);
                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDeleteConfirmDialog(position);
                    }
                });


                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }
                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mRefundImageList.get(position).path) && TextUtils.isEmpty(mRefundImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(OrderDetailActivity.this, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mRefundImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });

                if (mShowDelete) {
                    holder.getView(R.id.iv_delete).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.iv_delete).setVisibility(View.GONE);
                }
            }


        };


        mRvRefund.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvRefund.setAdapter(mRefundImageAdapter);
        mRvRefund.setHasFixedSize(true);
        mRvRefund.setNestedScrollingEnabled(false);
    }

    private void showDeleteConfirmDialog(final int position) {
        ConfirmDialog mConfirmDialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {
            }

            @Override
            public void onRightButtonClick(View view) {
                mImageList.remove(position);
                mPayImageAdapter.notifyDataSetChanged();
            }

        });
        mConfirmDialog.showDialog("确认删除？", "取消", "确认");
    }

    @Override
    protected void onToolbarClicked(int paramId) {
        super.onToolbarClicked(paramId);
        switch (paramId) {
            case RIGHT_TEXT:
                if (TextUtils.isEmpty(mPayeeId)) {
                    ToastUtil.showMessage(mContext, "请选择收款渠道");
                    return;
                }

                if (TextUtils.isEmpty(mTvIsUsePoint.getText().toString())) {
                    ToastUtil.showMessage(mContext, "请选择是否使用积分");
                    return;
                }

                if (mImageList.isEmpty()) {
                    ToastUtil.showMessage(mContext, "请添加付款凭证");
                    return;
                }

                httpCommitUploadFile(mImageList);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x262 && resultCode == Activity.RESULT_OK) {
            PayeeMethodBean payeeMethodBean = (PayeeMethodBean) data.getSerializableExtra("PayeeMethodBean");
            setPayeeView(payeeMethodBean);

        }

        if (requestCode == 0x268 && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> imageList = data.getParcelableArrayListExtra("ImageList");
            if (imageList != null) {
                mImageList.clear();
                mImageList.addAll(imageList);
                mPayImageAdapter.notifyDataSetChanged();
            }

        }

        if (requestCode == 0x176 && resultCode == Activity.RESULT_OK) {
            AddressBean addressBean = (AddressBean) data.getSerializableExtra("AddressBean");
            if (addressBean != null) {
                mLlAddressInfo.setVisibility(View.VISIBLE);
                mTvAddressName.setText(getString(R.string.format_deliver_name, "收货人：" + addressBean.getName()));
                mTvAddressPhone.setText(addressBean.getPhone());
                mTvAddress.setText(CommonUtil.getRegionString(addressBean.getRegion()) + addressBean.getDetail());
                addrId = addressBean.getId();
            }
        }
    }

    private void setPayeeView(PayeeMethodBean payeeMethodBean) {
        if (payeeMethodBean == null) {
            return;
        }
        mPayeeId = payeeMethodBean.getId();
        mTvPayee.setText(payeeMethodBean.getBank());
        mTvName.setText(payeeMethodBean.getName());
        mTvAccount.setText(payeeMethodBean.getAccount());
        mTvPayWay.setText(payeeMethodBean.getPayType());

        if (payeeMethodBean.getPayType() != null) {
            mLlPaidType.setVisibility(View.VISIBLE);
            if (StringUtil.isEquals(payeeMethodBean.getPayType(), "微信支付")) {
                mLlPayType.setVisibility(View.GONE);
                mLlAccount.setVisibility(View.GONE);
            }
        } else {
            mLlPaidType.setVisibility(View.GONE);
        }
        mTvPayWay.setText(payeeMethodBean.getPayType());

    }

    @OnClick(R.id.tv_more)
    void onMoreClick() {
        if (mGoodsList.size() > 6) {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsPartList);
            mTvMore.setText(getString(R.string.format_view_all_goods, mGoodsAllList.size()));
        } else {
            mGoodsList.clear();
            mGoodsList.addAll(mGoodsAllList);
            mTvMore.setText("收起");
        }

        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.ll_pay_type)
    void collectionWayClick() {
        if (mAskBuyDetailBean == null) {
            ToastUtil.showMessage(mContext, "网络错误，请稍后再试");
            return;
        }
        Intent intent = new Intent(mContext, CollectionWayActivity.class);
        if (mAskBuyDetailBean.getLeaderId() == null) {
            intent.putExtra("isCompany", true);
        } else {
            intent.putExtra("isCompany", false);
        }
        intent.putExtra("PayeeId", mPayeeId);
        startActivityForResult(intent, 0x262);
    }


    @OnClick(R.id.ll_use_points)
    void usePointsClick() {
        showUsePointsPopupWindow();
    }

    @OnClick(R.id.lly_address)
    void addresssClick() {
        Intent intent = new Intent(mContext, AddressManageActivity.class);
        intent.setType("select");
        startActivityForResult(intent, 0x176);
    }

    @OnClick(R.id.ll_pay_voucher)
    void payVoucherClick() {
        Intent intent = new Intent(mContext, PaymentVoucherActivity.class);
        intent.putExtra("ImageList", mImageList);
        startActivityForResult(intent, 0x268);
    }

    @OnClick(R.id.ll_offline_pay)
    void onLlOfflinePayClick() {
        mCbOfflinePay.setChecked(!mCbOfflinePay.isChecked());
    }


    @OnClick(R.id.ll_wechat_pay)
    void onLlWechatPayClick() {
        mCbWechatPay.setChecked(!mCbWechatPay.isChecked());
    }

    @OnClick(R.id.btn_pay)
    void payClick() {
        if (TextUtils.isEmpty(mTvIsUsePoint.getText().toString())) {
            ToastUtil.showMessage(mContext, "请选择是否使用积分");
            return;
        }

        if (!mCbWechatPay.isChecked() && !mCbOfflinePay.isChecked()) {
            ToastUtil.showMessage(mContext, "请选择支付方式");
            return;
        }
        if (mAskBuyBean.getCouponId() == null) {
            for (AskBuyDetailBean.ItemsBean itemsBean : mGoodsAllList) {
                if (StateUtil.getResSate(mContext, itemsBean.getProductState()).equals("已下架")) {
                    ToastUtil.showToastInCenter(mContext, "含下架产品，请删除后重新添加");
                    return;
                }
            }
        }


        String points = null;
        if (mLlPoints.isShown() && !TextUtils.isEmpty(mEtPoints.getText().toString())) {
            points = mEtPoints.getText().toString().trim();
        }
        mAskBuyDetailBean.setPointsInput(points);

        if (mCbWechatPay.isChecked()) {
            if (mAskBuyDetailBean.getCouponId() != null) {
                if (addrId == null) {
                    ToastUtil.showToastInCenter(mContext, "请选择收货地址");
                    return;
                }
            }
            httpWchatPay(addrId, mAskBuyDetailBean.getId(), points);
            return;
        }

        if (mCbOfflinePay.isChecked()) {
            Intent intent = new Intent(mContext, OfflinePayActivity.class);
            intent.putExtra("AskBuyDetailBean", mAskBuyDetailBean);
            startActivityForResult(intent, 0x268);
            return;
        }

    }

    private void showUsePointsPopupWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popupwindow_is_use_point, null);
        // 强制隐藏键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        if (mUsePointPopupWindow == null) {
            mUsePointPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mUsePointPopupWindow.setFocusable(true);
            mUsePointPopupWindow.setOutsideTouchable(true);
            /* mUsePointPopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
            mUsePointPopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
            mUsePointPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
                        mUsePointPopupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            mUsePointPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowUtil.setPopWindowBackgroundAlpha(OrderDetailActivity.this, 1f);
                }
            });

            view.findViewById(R.id.tv_yes).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mUsePointPopupWindow.dismiss();
                    mTvIsUsePoint.setText("是");
                    mLlPoints.setVisibility(View.VISIBLE);
                }
            });
            view.findViewById(R.id.tv_no).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mUsePointPopupWindow.dismiss();
                    mTvIsUsePoint.setText("否");
                    mLlPoints.setVisibility(View.GONE);
                    mEtPoints.setText(null);
                }
            });

            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mUsePointPopupWindow.dismiss();
                }
            });


        }
        WindowUtil.setPopWindowBackgroundAlpha(this, 0.7f);
        mUsePointPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }


    private void setDetailView(AskBuyDetailBean detailBean) {
        if (detailBean == null) {
            return;
        }

        setSateView(detailBean.getState());
        if (StringUtil.isEquals(detailBean.getState(), StateUtil.MY_STOCK_ORDER_PAY) && StringUtil.isEquals(mType, "my")) {
            if (detailBean.getCouponId() != null) {
                mLlyAddress.setVisibility(View.VISIBLE);
            } else {
                mLlyAddress.setVisibility(View.GONE);
            }
        }
        if (mAskBuyDetailBean.getLeaderName() != null) {
            mLlLeaderName.setVisibility(View.VISIBLE);
            mTvLeaderName.setText(mAskBuyDetailBean.getLeaderName());
        } else {
            if (StringUtil.isEquals(mAskBuyDetailBean.getPayType(), "微信支付")) {
                mLlLeaderName.setVisibility(View.GONE);
            } else {
                mLlLeaderName.setVisibility(View.VISIBLE);
            }
            mTvLeaderName.setText(mAskBuyDetailBean.getLeaderId() == null ? "系统用户" : "-");
        }

        if (StringUtil.isEquals(detailBean.getState(), StateUtil.MY_STOCK_ORDER_PAY)) {
            mTvPayActual.setText(getString(R.string.format_rmb, detailBean.getTotalPrice()));
            mIvRight1.setVisibility(View.VISIBLE);
            mIvRight2.setVisibility(View.VISIBLE);
        } else {
            mIvRight1.setVisibility(View.GONE);
            mIvRight2.setVisibility(View.GONE);

            if (detailBean.getPoints() != null) {
                mLlPoints.setVisibility(View.VISIBLE);
                mTvIsUsePoint.setText("是");
                mEtPoints.setText(String.valueOf(detailBean.getPoints()));
            } else {
                mLlPoints.setVisibility(View.GONE);
                mTvIsUsePoint.setText("否");
            }


            PayeeMethodBean payeeInfo = detailBean.getPayeeInfo();
            setPayeeView(payeeInfo);
            mTvPayActual.setText(getString(R.string.format_rmb, detailBean.getPaidPrice()));

            if (!TextUtils.isEmpty(detailBean.getPaymentFid())) {
                mLlPayImage.setVisibility(View.VISIBLE);
                ArrayList<ImageItem> splitImage = CommonUtil.getSplitImage(detailBean.getPaymentFid());
                mImageList.clear();
                mImageList.addAll(splitImage);
                mPayImageAdapter.notifyDataSetChanged();
            }

            if (!TextUtils.isEmpty(detailBean.getRefundFid())) {
                mLlRefundImage.setVisibility(View.VISIBLE);
                ArrayList<ImageItem> refundImages = CommonUtil.getSplitImage(detailBean.getRefundFid());
                mRefundImageList.clear();
                mRefundImageList.addAll(refundImages);
                mRefundImageAdapter.notifyDataSetChanged();
            }
        }

        mTvOrderNum.setText(getString(R.string.format_order_num, detailBean.getCode()));
        mTvOrderTime.setText(getString(R.string.format_order_time, DateUtil.getDateTimeString(detailBean.getCreatedOn())));
        mTvAmount.setText(getString(R.string.format_rmb, detailBean.getTotalPrice()));

        mGoodsAllList = detailBean.getItems();
        mTvMore.setText(getString(R.string.format_view_all_goods, mGoodsAllList.size()));
        mGoodsList.clear();
        if (mGoodsAllList.size() > 6) {
            mTvMore.setVisibility(View.VISIBLE);
            for (int i = 0; i < 6; i++) {
                mGoodsPartList.add(mGoodsAllList.get(i));
            }
            mGoodsList.addAll(mGoodsPartList);
        } else {
            mGoodsList.addAll(mGoodsAllList);
        }
        mAdapter.notifyDataSetChanged();
    }

    private void httpGetPointConvert() {
        try {
            CommonFactory.createBiz().pointConvert(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    mPointCovert = (double) data;
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void httpGetDetail(String id) {
        try {
            OrderBizFactory.createBiz().getMyBuyDetail(this, id, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    mAskBuyDetailBean = (AskBuyDetailBean) data;
                    setDetailView(mAskBuyDetailBean);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpCommitUploadFile(ArrayList<ImageItem> customImageList) {
        final ArrayList<File> fileList = new ArrayList<>();


        for (ImageItem imageItem : customImageList) {
            if (!TextUtils.isEmpty(imageItem.path)) {
                fileList.add(new File(imageItem.path));
            }
        }
        try {
            FileBizFactory.createBiz().uploads(this, fileList, Url.FILE_TYPE_IMAGE, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    List<UploadFileBean> fileBeanList = (List<UploadFileBean>) data;
                    List<String> fileIds = new ArrayList<>();
                    for (UploadFileBean uploadFileBean : fileBeanList) {
                        fileIds.add(uploadFileBean.getId());
                    }

                    String ids = StringUtil.arrayList(fileIds);

                    httpCommit(ids);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            dismissLoadingDialog();
        }

    }


    private void httpCommit(String fid) {
        String points = null;
        if (mLlPoints.isShown() && !TextUtils.isEmpty(mEtPoints.getText().toString())) {
            points = mEtPoints.getText().toString().trim();
        }
        try {
            OrderBizFactory.createBiz().buyPay(this, mAskBuyBean.getId(), mPayeeId, fid, points, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ToastUtil.showMessage(mContext, "提交成功");
                    EventBus.getDefault().post(new EventMessage(EventTag.MY_STOCK_ORDER_LIST, mAskBuyBean.getState()));
                    //                    httpGetDetail(mAskBuyBean.getId());
                    finish();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();

                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    private void httpGetMyPoints() {
        try {
            UserBizFactory.createBiz().getMyPoint(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    mPoints = (Integer) data;
                    if (mPoints != null) {
                        mEtPoints.setHint(getString(R.string.format_max_points_use, mPoints));
                        UserBean userBean = UserBizFactory.createBiz().getLoginUser(OrderDetailActivity.this);
                        userBean.setPoints(mPoints);
                        DBUtil.getInstance(mContext).save(userBean);
                    }
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void httpWchatPay(String addrId, String buyId, String points) {
        try {
            OrderBizFactory.createBiz().wxPay(this, addrId, buyId, points, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    WeChatPayOrderBean bean = (WeChatPayOrderBean) data;
                    if (bean != null) {
                        WechatPay wechatPay = new WechatPay(mContext);
                        wechatPay.pay(bean);
                    }
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

    /**
     * 微信支付回调广播
     */
    private BroadcastReceiver payBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            int errCode = intent.getIntExtra(WXPayEntryActivity.WX_PAY_ERR_CODE, -1);
            switch (errCode) {
                case 0: // 成功
                    try {
                        OrderBizFactory.createBiz().queryOrder(OrderDetailActivity.this, mAskBuyDetailBean.getId(), new UICallBack() {
                            @Override
                            public void onStart() {
                                showLoadingDialog();
                            }

                            @Override
                            public void onRefresh(Object data) {
                                dismissLoadingDialog();
                                EventBus.getDefault().post(new EventMessage(EventTag.MY_STOCK_ORDER_LIST, mAskBuyDetailBean.getState()));
                                finish();
                            }

                            @Override
                            public void onFailure(int status) {
                                dismissLoadingDialog();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;

                case -1: // 错误
                    ToastUtil.showMessage(mContext, getString(R.string.pay_fail));
                    break;

                case -2: // 用户取消
                    ToastUtil.showMessage(mContext, getString(R.string.pay_cancel));
                    break;

                default:
                    ToastUtil.showMessage(mContext, getString(R.string.pay_fail));
                    break;
            }
        }

    };

}
